package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.task.CourseDetailTask;
import com.xudow.app.ui.task.CourseFavoriteTask;
import com.xudow.app.ui.task.OrderCreateTask;
import com.xudow.app.ui.task.RelatedCourcesTask;
import com.xudow.app.ui.task.ScannerToCourseDetailTask;
import com.xudow.app.ui.task.ShoppingCartAddTask;
import com.xudow.app.util.DateUtil;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.LngLatUtil;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 课程详情Activity
 *
 * @author lukecheng
 */
public class CourseDetailActivity2 extends BaseActivity {

    private Long courseId; //课程ID
    private Long classid;//OA扫描二维码传递过来查询课程详情
    private CourseDetailTask courseDetailTask;
    private RelatedCourcesTask relatedCourcesTask;
    private CourseFavoriteTask courseFavoriteTask;
    private ShoppingCartAddTask shoppingCartAddTask;
    private OrderCreateTask orderCreateTask;

    private TextView courseNameTextView;
    private TextView coursePriceTextView;
    private TextView courseActualTextView;
    private TextView agencyNameTextView;
    private LinearLayout courseTagsLayout;
    private ImageView agencyImage;
    private TextView agencyImageSize;
    private TextView courseStartTime;
    private TextView agencyAddress;
    private TextView courseTeacherTextView;
    private TextView courseObjectiveTextView;
    private TextView courseArrangementTextView;
    private TextView courseTeachingResultsTextView;
    private TextView xdRecommendView;
    private LinearLayout relatedCoursesLayout;
    private TextView distanceTextView;
    private TextView addtocarlist_tv;//加入购物车
    private CourseWithOtherInfo course; //课程
    private String schoolImage; //校区图片
    private int schoolImageCount = 0; //校区图片数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);

        courseId = getIntent().getLongExtra("courseId", 0L);
        classid=getIntent().getLongExtra("classid",0L);
        courseNameTextView = (TextView) findViewById(R.id.course_name);
        coursePriceTextView = (TextView) findViewById(R.id.course_price);
        courseActualTextView = (TextView) findViewById(R.id.course_actual_price);
        agencyNameTextView = (TextView) findViewById(R.id.agency_name);
        courseTagsLayout = (LinearLayout) findViewById(R.id.course_tags);
        agencyImage = (ImageView) findViewById(R.id.agency_image);
        agencyImageSize = (TextView) findViewById(R.id.agency_image_size);
        courseStartTime = (TextView) findViewById(R.id.course_start_time);
        agencyAddress = (TextView) findViewById(R.id.agency_address);
        courseTeacherTextView = (TextView) findViewById(R.id.course_teacher);
        courseObjectiveTextView = (TextView) findViewById(R.id.course_objective);
        courseArrangementTextView = (TextView) findViewById(R.id.course_arrangement);
        courseTeachingResultsTextView = (TextView) findViewById(R.id.course_teaching_results);
        relatedCoursesLayout = (LinearLayout) findViewById(R.id.related_courses);
        xdRecommendView = (TextView) findViewById(R.id.xd_recommend);
        distanceTextView = (TextView) findViewById(R.id.distance);
       // addtocarlist_tv=(TextView)findViewById(R.id.add_carlist);
        HashMap<String, String> params = Maps.newHashMap();


        showLodingDialog(getString(R.string.loading));

        XApplication application = (XApplication) getApplication();
        if (application.isStudent()) {
            findViewById(R.id.pay_now).setVisibility(View.GONE);
        }
        if (0!=courseId) {
            params.put("courseid", "" + courseId);
            courseDetailTask = new CourseDetailTask(this, courseDetailHandler);
            addTask(courseDetailTask);
            courseDetailTask.execute(params); // 获取课程详情
        }
        if (0!=classid){
            params.put("classid", "" + classid);
            ScannerToCourseDetailTask task=new ScannerToCourseDetailTask(this,courseDetailHandler);
            addTask(task);
            task.execute(params);//扫描获取课程详情 task
        }
        relatedCourcesTask = new RelatedCourcesTask(this, courseListHandler);
        addTask(courseDetailTask);
        relatedCourcesTask.execute(params); // 获取相关课程
    }

    public void onBackBtnClick(View view) {
        finish();
    }
    /**
     * 查看课程选座情况
     */
    public void getSiteInfClik(View view){
            Intent intent=new Intent(this,SitesActivity.class);
            intent.putExtra("courseId",courseId+"");
        startActivity(intent);
    }
    /**
     * 立即支付按钮点击事件
     *
     * @param view
     */
    public void payIt(View view) {
        //课程有个status的状态，如果是 COURSE_STATUS_INVALID = 0 则表示无效了
        if (0 == course.getStatus()) {
            String msg = getString(R.string.course_invalid);
            getMyApp().makeToast(msg);
            return;
        }

        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        }
        Intent intent = new Intent(getApplicationContext(), ChoseChildActivity.class);
        intent.putExtra("courseId_to_order", courseId);
        startActivity(intent);
    }

    /**
     * 获取课程详情Handler
     */
    private Handler courseDetailHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (CourseDetailTask.SUCCESS == msg.what) {
                course = (CourseWithOtherInfo) msg.getData().getSerializable("course");
                schoolImage = msg.getData().getString("schoolImage");
                schoolImageCount = msg.getData().getInt("schoolImageCount", 0);
                courseId=course.getId();
                courseNameTextView.setText(course.getName());
                coursePriceTextView.setText("￥" + course.getCoursePrice());
                courseActualTextView.setText("￥" + course.getActualPrice());
                String agencyName="";
                if (null==course.getAgencyName()&&null!=course.getUserSendSchoolName())
                    agencyName=course.getUserSendSchoolName();
                else
                    agencyName=course.getAgencyName();
                agencyNameTextView.setText(agencyName);
                String teacher="";
                if (null==course.getTeacher())
                    teacher="未知";
                else
                    teacher=course.getTeacher();
                    courseTeacherTextView.setText("\n" + teacher + "\n");

                courseObjectiveTextView.setText("\n" + course.getObjective() + "\n");
                courseArrangementTextView.setText("\n" + course.getArrangement() + "\n");

                if (null != course.getBeginDate()) {
                    String dateStr = DateUtil.dateTimeToStr(course.getBeginDate(), DateUtil.DATE_FORMAT_YYYY_MM_DD);
                    String s=(course.getGiveTime()==null? "":course.getGiveTime());
                    courseStartTime.setText(dateStr+"  "+s);
                    Log.e( "courseTime: ","--"+course.getCourseTimeLength() );
                }
                String address="";
                if (null==course.getSchoolAdress()&&null!=course.getUserSendSchoolAddress())
                    address=course.getUserSendSchoolAddress();
                else
                    address=course.getSchoolAdress();
                agencyAddress.setText(address);

                if (!StringUtils.isEmpty(course.getTeachingResults())) {
                    courseTeachingResultsTextView.setText("\n" + course.getTeachingResults() + "\n");
                }

                if (!StringUtils.isEmpty(course.getXudowRecommend())) {
                    xdRecommendView.setText("\n" + course.getXudowRecommend() + "\n");
                } else {
                    xdRecommendView.setText("\n\n");
                }

                String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, schoolImage);
                ImageUtils.loadImage(CourseDetailActivity2.this, agencyImage, imageUrl, R.mipmap.course_def_img);

                String imageSizeStr = getString(R.string.course_detail_image_size, schoolImageCount);
                agencyImageSize.setText(imageSizeStr);

                //计算距离
                XApplication application = (XApplication) getApplicationContext();
                if (null != application &&
                        null != course.getLongtitude() && null != course.getLatitude() &&
                        null != application.longitude && null != application.latitude) {
                    String distance = LngLatUtil.distanceFormatted(course.getLongtitude().doubleValue(), course.getLatitude().doubleValue(),
                            application.longitude, application.latitude);

                    if (!StringUtils.isEmpty(distance)) {
                        distanceTextView.setText(distance);
                    }
                }

                List<String> tags = new ArrayList<String>();
                tags.add(course.getGradeName());

                String courseType = course.getTypeName();
                if (!StringUtils.isEmpty(courseType)) {
                    tags.add(courseType);
                }

                createCourseTags(tags);
            }
        }
    };

    /**
     * 创建课程tag
     *
     * @param tags
     */
    private void createCourseTags(List<String> tags) {
        for (String tag : tags) {
            TextView view = new TextView(this);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            layoutParams.setMargins(10, 0, 0, 0);

            view.setLayoutParams(layoutParams);
            view.setPadding(10, 0, 10, 0);
            view.setTextSize(12);
            view.setText(tag);
            view.setTextColor(getResources().getColor(R.color.rvcode));
            view.setBackgroundResource(R.drawable.round_light_rvcode_bg);

            courseTagsLayout.addView(view);
        }
    }

    /**
     * 获取相关课程Handler
     */
    private Handler courseListHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RelatedCourcesTask.SUCCESS) {
                onCourseListSuccess(msg.getData());
            }
        }
    };

    private void onCourseListSuccess(Bundle data) {
        CourseWithOtherInfo[] courseArr = (CourseWithOtherInfo[]) data.getSerializable("courses");

        for (final CourseWithOtherInfo info : courseArr) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_related_course, null);
            view.setPadding(10, 0, 10, 0);
            view.setClickable(true);

            ((TextView) view.findViewById(R.id.cource_name)).setText(info.getName());
            ((TextView) view.findViewById(R.id.cource_price)).setText("￥" + info.getCoursePrice());
            ((TextView) view.findViewById(R.id.cource_actual_price)).setText("￥" + info.getActualPrice());

            ImageView courseImage = ((ImageView) view.findViewById(R.id.cource_image));
            courseImage.setMinimumHeight(120);
            courseImage.setMinimumWidth(120);
            courseImage.setMinimumHeight(120);
            courseImage.setMinimumWidth(120);

            if (StringUtils.isEmpty(info.getThumbnail()) || "null".equals(info.getThumbnail())) {
                courseImage.setImageResource(R.mipmap.course_def_img);
            } else {
                String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, info.getThumbnail());
                ImageUtils.loadImage(CourseDetailActivity2.this, courseImage, imageUrl, R.mipmap.course_def_img);
            }

            view.setOnClickListener(new View.OnClickListener() { // 相关课程点击事件
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(CourseDetailActivity2.this, CourseDetailActivity2.class);
                    intent.putExtra("courseId", info.getId());
                    startActivity(intent);
                }
            });

            relatedCoursesLayout.addView(view);
        }
    }

    /**
     * 分享按钮点击
     *
     * @param view
     */
    public void onShareClick(View view) {
        if (null == course) {
            return;
        }

        //TODO:分享什么?
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        intent.putExtra(Intent.EXTRA_TEXT, course.getName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, getString(R.string.shared_to)));
    }
    /**
     * 获取购物车列表信息点击
     */
    public void onGetCarClick(View view){
        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        }else{
            //TODO 进入购物车页面
            Intent intent=new Intent(this,CartActivity.class);
            startActivity(intent);
        }


    }
    /**
     * 获取购物车列表handler
     */
    private Handler carlistHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    /**
     * 加入收藏夹按钮点击
     *
     * @param view
     */
    public void favoriteCourse(View view) {
        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        }

        showLodingDialog(getString(R.string.processing));

        HashMap<String, String> params = Maps.newHashMap();
        params.put("courseid", "" + course.getId());

        courseFavoriteTask = new CourseFavoriteTask(this, courseFavoriteHandler);
        addTask(courseFavoriteTask);
        courseFavoriteTask.execute(params);
    }

    /**
     * 加入收藏夹Handler
     */
    public Handler courseFavoriteHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (CourseFavoriteTask.SUCCESS == msg.what) {
                String message = getString(R.string.favorite_success);
                Toast.makeText(CourseDetailActivity2.this, message, Toast.LENGTH_SHORT).show();
            } else {
                if (msg.getData().get("errMessage") != null) {
                    String message = (String) msg.getData().get("errMessage");
                    Toast.makeText(CourseDetailActivity2.this, message, Toast.LENGTH_SHORT).show();
                } else {
                    String message = getString(R.string.favorite_fail);
                    Toast.makeText(CourseDetailActivity2.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 更多链接点击事件
     *
     * @param view
     */
    public void onMoreClick(View view) {
        Intent intent = new Intent(this, CourseListActivity.class);
        //优选课程
        intent.putExtra("mode","recommend");
        startActivity(intent);
    }

    /**
     * 添加到购物车点击
     *
     * @param view
     */
    public void onAddCartClick(View view) {
        if (null==course.getStatus()||0 == course.getStatus()) {
            String msg = getString(R.string.course_invalid);
            getMyApp().makeToast(msg);
            return;
        }

        XApplication application = (XApplication) getApplication();
        if (!application.isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("closeAfterLogin", true);
            startActivity(intent);
            return;
        }
        Intent intent = new Intent(this, ChoseChildActivity.class);
        Log.e( "onAddCartClick","course.getid:"+course.getId()+" courseId:"+courseId );
        intent.putExtra("courseId", course.getId());
        startActivity(intent);

    }


    /**
     * 地址点击事件
     *
     * @param view
     */
    public void onAddressClick(View view) {
        String address="";
        if (null==course.getSchoolAdress()&&null!=course.getUserSendSchoolAddress())
            address=course.getUserSendSchoolAddress();
        else
            address=course.getSchoolAdress();
        String url = String.format(Config.MAP_URL, course.getLongtitude(), course.getLatitude(),
                address);

        Log.e("ZXJ", "地图url = " + url);

        Intent intent = new Intent(this, MapViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", course.getSchoolAdress());

        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            finish();
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 校区图片点击事件
     *
     * @param view
     */
    public void onSchoolImageClick(View view) {
        if (schoolImageCount <= 0) {
            return;
        }

        Intent intent = new Intent(this, CourseImagesActivity.class);
        intent.putExtra("courseId", course.getId());
        startActivity(intent);
    }
}
